// include/storage.h
#ifndef STORAGE_H
#define STORAGE_H

#include "storage_types.h"
#include "storage_config.h"
#include "storage_error.h"
#include "storage_protection.h"
#include "storage_perf.h"
#include "esp_system.h"
#include "esp_vfs.h"
#include "esp_littlefs.h"


// 异步操作状态
typedef enum {
    ASYNC_STATE_IDLE,
    ASYNC_STATE_IN_PROGRESS,
    ASYNC_STATE_COMPLETED,
    ASYNC_STATE_ERROR
} async_state_t;

// DMA传输模式
typedef enum {
    DMA_MODE_SINGLE,    // 单次传输
    DMA_MODE_SCATTER,   // 分散写入
    DMA_MODE_GATHER,    // 聚集读取
    DMA_MODE_CIRCULAR   // 循环传输
} dma_transfer_mode_t;


// 异步操作回调函数类型
typedef void (*async_callback_t)(void *context, esp_err_t result);


// 核心文件系统操作
esp_err_t file_system_init(file_system_t *fs, const fs_config_t *config);
void file_system_deinit(file_system_t *fs);
esp_err_t file_system_format(file_system_t *fs);


// 基本文件操作
esp_err_t file_system_write(file_system_t *fs,  const char *path, const void *data, size_t size);
esp_err_t file_system_read(file_system_t *fs,   const char *path, void *data, size_t size, size_t *read_size);
esp_err_t file_system_append(file_system_t *fs, const char *path, const void *data, size_t size);
esp_err_t file_system_remove(file_system_t *fs, const char *path);
esp_err_t file_system_rename(file_system_t *fs, const char *old_path, const char *new_path);
esp_err_t file_system_stat(file_system_t *fs,   const char *path, struct stat *st);
esp_err_t file_system_exists(file_system_t *fs, const char *path, bool *exists);

// 目录操作
esp_err_t file_system_mkdir(file_system_t *fs, const char *path);
esp_err_t file_system_rmdir(file_system_t *fs, const char *path);
esp_err_t file_system_list_directory(file_system_t *fs, const char *path, file_info_t *files, size_t *count);

// DMA操作
esp_err_t file_system_write_dma(file_system_t *fs, const char *path, 
                               size_t (*data_cb)(void*, size_t, void*), 
                               void *user_data);

esp_err_t file_system_read_dma(file_system_t *fs, const char *path, 
                              bool (*process_cb)(const void*, size_t, void*), 
                              void *user_data);

// 异步操作
esp_err_t async_write(file_system_t *fs, const char *path, const void *data, 
                     size_t size, async_callback_t callback, void *context);

esp_err_t async_read(file_system_t *fs, const char *path, void *data,
                    size_t size, async_callback_t callback, void *context);

esp_err_t async_cancel(file_system_t *fs, const char *path);

esp_err_t async_wait(file_system_t *fs, const char *path, TickType_t timeout);

async_state_t async_get_state(file_system_t *fs, const char *path);

// 存储设备管理
esp_err_t storage_device_register(storage_device_t *dev, const storage_config_t *config);
esp_err_t storage_device_unregister(storage_device_t *dev);
esp_err_t file_system_set_storage_device(file_system_t *fs, storage_device_t *dev);
esp_err_t file_system_get_storage_info(file_system_t *fs, uint32_t *total_bytes, uint32_t *used_bytes);

#endif /* STORAGE_H */


// include/storage_types.h
#ifndef STORAGE_TYPES_H
#define STORAGE_TYPES_H

#include <stdint.h>
#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "esp_err.h"

// 基本定义
#define FILE_PATH_MAX 256
#define FILE_NAME_MAX 64







// 扩展缓存管理器结构
struct fs_cache_t {
    
    fs_cache_entry_t *entries;   // 缓存条目数组
    size_t count;                // 当前缓存条目数
    size_t capacity;             // 最大缓存条目数 
    size_t max_cache_size;       // 最大缓存大小
    struct {
        uint32_t cache_hits;
        uint32_t cache_misses;
        uint32_t buffer_flushes;
        uint64_t total_read_time;
        uint64_t total_write_time;
    } stats;       // 性能统计信息
    bool prefetch_enabled;       // 是否启用预读取
};

// 扩展缓存条目结构
struct fs_cache_entry_t {
    char *path;                  // 文件路径
    uint8_t *data;              // 缓存数据
    size_t size;                // 数据大小
    size_t capacity;            // 缓冲区容量
    bool dirty;                 // 是否需要回写
    time_t last_access;         // 最后访问时间
    uint32_t access_count;      // 访问计数
    bool is_prefetch;           // 是否为预读取数据
};




// 存储设备类型枚举
typedef enum {
    STORAGE_TYPE_FLASH,
    STORAGE_TYPE_SD,
    STORAGE_TYPE_MAX
} storage_device_type_t;

// 文件信息结构
typedef struct {
    char name[FILE_NAME_MAX];
    size_t size;
    bool is_directory;
    time_t modified_time;
} file_info_t;

// 存储设备操作接口
typedef struct {
    esp_err_t (*init)(void *config);
    esp_err_t (*deinit)(void);
    esp_err_t (*read)(void *buf, size_t size, size_t *read_size);
    esp_err_t (*write)(const void *buf, size_t size);
    esp_err_t (*flush)(void);
} storage_ops_t;


// 存储设备配置
typedef struct {
    union {
        struct {
            const char *partition_label;
        } flash_config;
        
        struct {
            int miso_pin;
            int mosi_pin;
            int sck_pin;
            int cs_pin;
        } sd_config;
    };
} storage_config_t;


// 存储设备实例
typedef struct {
    storage_device_type_t type;
    storage_ops_t ops;
    storage_config_t config;
} storage_device_t;


// 文件系统配置
typedef struct {
    char base_path[64];        
    char partition_label[16];  
    bool format_if_mount_failed;
    storage_device_t *storage_dev;
    struct {
        int miso_pin;
        int mosi_pin;
        int sck_pin;
        int cs_pin;
    } sd_config;
} fs_config_t;

// 前向声明
struct fs_cache_t;
struct dma_manager_t;

// 文件系统实例
typedef struct {
    fs_config_t config;
    bool mounted;            
    SemaphoreHandle_t mutex;    
    struct fs_cache_t *cache;
    struct dma_manager_t *dma_mgr;
    transaction_data_t *transaction;
} file_system_t;

#endif /* STORAGE_TYPES_H */

// include/storage_protection.h
#ifndef STORAGE_PROTECTION_H
#define STORAGE_PROTECTION_H

#include "storage_types.h"
#include "esp_crc.h"
#include "esp_system.h"

// CRC校验配置
#define CRC32_INITIAL_VALUE 0xFFFFFFFF
#define PROTECTION_MAGIC_NUMBER 0xAA55AA55
#define JOURNAL_BLOCK_SIZE 4096

// 数据保护状态
typedef enum {
    PROTECTION_STATUS_OK = 0,
    PROTECTION_STATUS_CRC_ERROR,
    PROTECTION_STATUS_POWER_FAIL,
    PROTECTION_STATUS_INCONSISTENT
} protection_status_t;

// 掉电保护元数据
typedef struct {
    uint32_t magic;              // 魔数用于识别有效数据
    uint32_t sequence;           // 序列号用于journal恢复
    uint32_t data_size;          // 实际数据大小
    uint32_t crc32;             // CRC32校验值
    time_t timestamp;           // 时间戳
} protection_metadata_t;

// 文件系统保护扩展
typedef struct {
    protection_metadata_t *metadata;
    char journal_path[FILE_PATH_MAX];  // journal文件路径
    SemaphoreHandle_t protection_mutex;
} fs_protection_t;

// 数据保护函数声明
esp_err_t fs_protection_init(file_system_t *fs);
void fs_protection_deinit(file_system_t *fs);

// CRC校验相关
esp_err_t fs_calc_crc32(const void *data, size_t size, uint32_t *crc);
esp_err_t fs_verify_crc32(const void *data, size_t size, uint32_t expected_crc);

// 掉电保护相关
esp_err_t fs_write_protected(file_system_t *fs, const char *path, 
                            const void *data, size_t size);
esp_err_t fs_read_protected(file_system_t *fs, const char *path,
                           void *data, size_t size, size_t *read_size);

// 一致性检查
esp_err_t fs_check_consistency(file_system_t *fs);
esp_err_t fs_recover_consistency(file_system_t *fs);

#endif /* STORAGE_PROTECTION_H */


// storage_power_protection.h
#ifndef STORAGE_POWER_PROTECTION_H
#define STORAGE_POWER_PROTECTION_H

#include "esp_err.h"
#include "storage.h"

#define TRANSACTION_MAGIC 0xABCD1234
#define TRANSACTION_PATH "/.transaction"
#define BACKUP_PATH "/.backup"

typedef enum {
   TRANSACTION_NONE = 0,
   TRANSACTION_STARTED,
   TRANSACTION_COMMITTED
} transaction_status_t;

typedef struct {
   uint32_t magic;          // Magic number for validation
   uint32_t sequence;       // Transaction sequence number
   uint32_t checksum;       // CRC32 of data
   uint32_t status;         // Transaction status
   size_t data_size;        // Size of data
   char path[FILE_PATH_MAX]; // Target file path
} transaction_header_t;

typedef struct {
   transaction_header_t header;
   uint8_t *data;          // Transaction data buffer
   size_t size;            // Buffer size
   bool in_progress;       // Transaction state
} transaction_data_t;

esp_err_t fs_transaction_begin(file_system_t *fs);
esp_err_t fs_transaction_commit(file_system_t *fs);
esp_err_t fs_power_fail_recover(file_system_t *fs);

#endif

// storage_perf.h
#ifndef STORAGE_PERF_H
#define STORAGE_PERF_H

#include "storage_types.h"
#include "storage_config.h"
#include "esp_err.h"


// 性能统计信息
typedef struct {
    uint32_t cache_hits;         // 缓存命中次数
    uint32_t cache_misses;       // 缓存未命中次数 
    uint32_t dma_transfers;      // DMA传输次数
    uint32_t buffer_flushes;     // 缓冲区刷新次数
    uint64_t total_read_time;    // 总读取时间
    uint64_t total_write_time;   // 总写入时间
} fs_perf_stats_t;


// 性能优化相关函数
esp_err_t fs_enable_prefetch(file_system_t *fs, bool enable);
esp_err_t fs_prefetch_file(file_system_t *fs, const char *path);
void fs_reset_perf_stats(file_system_t *fs);

// 获取性能统计
esp_err_t fs_get_stats(file_system_t *fs, uint32_t *hits, uint32_t *misses, 
                      uint32_t *flushes, uint64_t *read_time, uint64_t *write_time);

#endif /* STORAGE_PERF_H */


// include/storage_error.h
#ifndef STORAGE_ERROR_H
#define STORAGE_ERROR_H

#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_err.h"

// 错误类型枚举
typedef enum {
    FS_ERROR_NONE = 0,
    FS_ERROR_DEVICE_FAIL,    // 设备级错误
    FS_ERROR_FS_CORRUPT,     // 文件系统损坏
    FS_ERROR_DMA_FAIL,       // DMA传输错误
    FS_ERROR_TIMEOUT,        // 操作超时
    FS_ERROR_MAX
} fs_error_type_t;

// 错误信息结构
typedef struct {
    fs_error_type_t type;    // 错误类型
    uint32_t code;           // 错误码
    uint32_t retry_count;    // 重试次数
    char location[64];       // 错误发生位置
    time_t timestamp;        // 错误发生时间
} fs_error_info_t;

// 错误上下文
typedef struct {
    fs_error_info_t errors[16];  // 循环错误历史记录
    size_t error_count;          // 错误计数
    SemaphoreHandle_t error_mutex; // 错误操作互斥锁
} fs_error_ctx_t;

// 扩展文件系统结构
typedef struct {
    fs_error_ctx_t *error_ctx;  // 错误上下文
} fs_ext_t;

// 错误处理函数声明
esp_err_t fs_error_init(file_system_t *fs);
void fs_error_deinit(file_system_t *fs);
void fs_error_record(file_system_t *fs, fs_error_type_t type, uint32_t code, const char* location);
esp_err_t fs_error_recover(file_system_t *fs, fs_error_type_t type);
esp_err_t fs_get_last_error(file_system_t *fs, fs_error_info_t *error);

#endif /* STORAGE_ERROR_H */

// include/storage_config.h
#ifndef STORAGE_CONFIG_H
#define STORAGE_CONFIG_H

// 缓存配置
#define MAX_CACHE_ENTRIES 16
#define MAX_CACHE_SIZE (64 * 1024)  // 64KB总缓存
#define FS_READ_BUFFER_SIZE (4 * 1024)

// DMA相关配置
#define DMA_BUFFER_SIZE (32 * 1024)  // 32KB per buffer
#define NUM_DMA_BUFFERS 2
#define DMA_OPTIMAL_BLOCK_SIZE  (16 * 1024)  // 16KB最佳传输块大小
#define DMA_MAX_SCATTER_GATHER  8            // 最大分散/聚集数量
#define DMA_PREFETCH_SIZE      (32 * 1024)   // 32KB预取大小

// 异步操作配置
#define MAX_ASYNC_OPERATIONS 8
#define ASYNC_TASK_STACK_SIZE 4096
#define ASYNC_TASK_PRIORITY 5

#endif /* STORAGE_CONFIG_H */

